var attendanceType;
var id;
var groupid;
var iconid;
var subid;
var menuid;
var index;
var taskDetailsListTijaio;
var taskDetailsList;
var points = [];
//var taskTypeShow

$(function () {
	groupid = ly.getUrlParam("groupid");
	iconid = ly.getUrlParam("iconid");
	subid = ly.getUrlParam("subid");
	menuid = ly.getUrlParam("menuid");

	//
	attendanceType = ly.getUrlParam("attendanceType");
	console.log("attendanceType="+attendanceType);
	id = ly.getUrlParam("id");
	if(attendanceType == 1){
	}
	if (attendanceType == 2) {
		$("#Map1").hide();
		$(".body_title").text("查询");
		$(".form").getForm({
			'ajaxform': true,
			id: id
		}, function (data) {
			console.log(data)

			// if (data.taskType == 3) {
			// 	$(".taskLine").removeClass('hide')
			// }

			//根据指定类型不同隐藏和显示指定任务执行人的界面
			changeIsSpecify(data.isSpecify, data.businessId);
			$("#save-btn-commodityClassification").hide();
			if(data.taskType == 3){
				$(".taskLine").removeClass('hide')
				$("#Map1BOX").removeClass('hide');
				if (data.taskDetailsList != null && data.taskDetailsList != '') {
					taskDetailsList = data.taskDetailsList;
					writeTaskDetailsList(data.taskDetailsList);
					//mapsShow()
				}
			}else{
				$(".taskLine").addClass('hide')
				$("#Map1BOX").addClass('hide');
			}
			//selectUsersList(data.userId,"","","1");
			$("#taskType").getSelect({
				type: "radio",
				asName: "taskType",
				code: "taskType",
				default: data.taskType
			});
			$("#taskLevel").getSelect({
				type:"radio",
				asName:"taskLevel",
				code:"taskLevel",
				default: data.taskLevel
			});
			$("#taskCategories").getSelect({
				type: "radio",
				asName: "taskCategories",
				code: "taskCategories",
				default: data.taskCategories,
			},function(){
				$('#taskCategories').find('label.rad').eq(0).remove();
			});
			$("#isSpecify").getSelect({
				type: "radio",
				asName: "isSpecify",
				list: [{
						value: "1",
						display: "指定人员"
					},
					{
						value: "2",
						display: "指定部门"
					},
					{
						value: "3",
						display: "指定工种"
					}
				],
				default: data.isSpecify
			});

		//------------------------------------------------------
		});
		$(".addDetailsList").remove();
		$(".radio").attr("disabled", "disabled");
	} else {
		$(".taskLine").hide();
		$("#Map1BOX").hide();
		changeIsSpecify("3");
		$("#taskType").getSelect({
			type: "radio",
			asName: "taskType",
			code: "taskType",
			default: '2'
		});
		$("#taskLevel").getSelect({
			type: "radio",
			asName: "taskLevel",
			code: "taskLevel",
			default: '1'
		});
		$("#taskCategories").getSelect({
			type: "radio",
			asName: "taskCategories",
			code: "taskCategories",
			default: '2',

		},function(){
			$('#taskCategories').find('label.rad').eq(0).remove();
		});
		$("#isSpecify").getSelect({
			type: "radio",
			asName: "isSpecify",
			list: [{
					value: "1",
					display: "指定人员"
				},
				{
					value: "2",
					display: "指定部门"
				},
				{
					value: "3",
					display: "指定工种"
				}
			],
			default: '3'
		});
		$('#addr').singleMapSelector({
			address: '',
			lng: '',
			lat: ''
		}, function (d) {
			orgAdd = d.address;
			latitude = d.lat;
			longitude = d.lng;
			$("#log").val(longitude);
			$("#lat").val(latitude);
			// $("#equipmentAddress").val(orgAdd);
			$("#writeAddress").removeClass("hide");
		});
	}
	setTimeout(function(){
	},1000)
  $("#timedTask").on("input", "input[name='timedTask']", function () {
	var timedTaskVal = $("input[name=timedTask]:checked").val();
	if(timedTaskVal == 2){
		$('.timedTaskBox').show()
	}else{
		$('.timedTaskBox').hide()
	}

  })
  $('.timedTaskBoxTime').clockTimePicker({});

	$("#taskType").on("input", "input[name='taskType']", function () {
		if ($(this).val() == '3') {
			$(".addDetailsList").removeClass("hide");
			$("#Map1").hide();
			$("#Map1BOX").hide();
			$('#writeAddress').hide();
			request({
				url: site.gateUrl + '/back/taskLine/selectTaskLineBackList',
				data: {
					size: 1000,
					num: 1
				},
				ajaxform: true,
				type: 'post',
				callback: function (r) {
					if (r.code == "rest.success") {
						var list = r.result.list,
							html = '<option value="">请选择</option>';
						for (var i = 0; i < list.length; i++) {
							html += '<option value="' + list[i].id + '">' + list[i].lineName + '</option>'
						}
						$("#lineId").html(html);
					} else {
						ly.toast(r.msg);
					}
				}
			});
			$('#taskCategories input[name="taskCategories"]').eq(1).prop("checked", true);
		} else {
			$("#Map1").show();
			$(".addDetailsList").addClass("hide");
			$('#taskCategories input[name="taskCategories"]').eq(0).prop("checked", true);
			//$("#addDetailsList").show();
		}
	});

	//提交
	$("body").on("click", "#save-btn-commodityClassification", function (event) {
		event.preventDefault();
		var success = $('.form').validate('submitValidate');
		if (success) {
			//验证通过提交表单
			submitFom();
		}
	})

	$("body").on("change", "#isSpecify", function () {
		var isSpecify = $("#isSpecify input:checked").val();
		changeIsSpecify(isSpecify);
	});
	//确认任务线路
	$("body").on("click", "#submit-btn-audit", function () {
		taskDetailsListTijaio = new Array();
		var obj = {};
		$(".id").each(function () {
			var id = $(this).val();
			obj = {
				'equipmentId': id,
				'taskOperation': $("#taskOperation" + id).find("option:selected").val(),
				'taskFlow': $(".taskFlow" + id).html(),
				'detailsExplain': $("#detailsExplain" + id).val()
			}
			taskDetailsListTijaio.push(obj);
			obj = {};
		});
		console.log(taskDetailsListTijaio);
		layer.close(index);
	});

	//  $("body").on("click","#addDetailsList",function(){
	//  	
	//  	creatDetailsList(taskDetailsList);
	//  });
	
	$("body").on("change","#taskType",function(){
		var taskType = $("input[name=taskType]:checked").val();
		// if(taskType == 3){
		// 	var taskCategories = $("input[name=taskCategories]:checked").val();
		// 	//alert(taskCategories);
		// 	if(taskCategories == 1){
		// 		$(".taskEndTime").removeClass("hide");
		// 	}else{
		// 		$(".taskEndTime").addClass("hide");
		// 	}
		// }else{
	    // 	$(".taskEndTime").addClass("hide");
		// }
		if(taskType ==3){
			//alert(123)
			$('#taskCategories').find('label').eq(0).hide();
		}else{
			$('#taskCategories').find('label').eq(0).show();
		}
	});
	$("body").on("change","#taskCategories",function(){
		var taskCategories = $("input[name=taskCategories]:checked").val();
		if(taskCategories == 1){
			var taskType = $("input[name=taskType]:checked").val();
			//alert(taskCategories);
			if(taskType == 3){
				$(".taskEndTime").removeClass("hide");
			}else{
				$(".taskEndTime").addClass("hide");
			}
			$('.timedTaskRadio').show();
			$('.timedTaskBox').show();  
		}else{
			$('.timedTaskRadio').hide();  
			$('.timedTaskBox').hide();  
			$(".taskEndTime").addClass("hide");
		}
	});

	function writeTaskDetailsList(taskDetailsList) {
		var maps = new AMap.Map('allmap');
		var markers;
		var detailsList = "";
	
		$.each(taskDetailsList, function (i, o) {
			detailsList += "<tr><td>" + o.taskFlow + "</td>" +
				"<td>" + o.taskLat + "</td><td>" + o.taskLog + "</td><td>" + o.taskOperationDisplay + "</td>" +
				"<td>" + o.detailsExplain + "</td></tr>";

				console.log('points:',points)
				points.push({
					lng: o.taskLog,
					lat: o.taskLat,
					data: 1,
				})
		});
		$("#detailsList").append(detailsList);
	
		///console.log(points)

	
		
		for (var i = 0; i < points.length; i++) {
			
			var jfong=[ points[i].lng,points[i].lat];	
			markers = new AMap.Marker({
				resizeEnable: true, //是否监控地图容器尺寸变化
				zoom:6, //初始地图级别
				position: jfong,
				zIndex: 101,
				map:maps,
		
				});	
				
				var markerContent = document.createElement("div");
				markerContent.className = "markerBOX";
				var markerImg = document.createElement("img");
				markerImg.className = "markerlnglat";
				markerImg.src ="../../img/mark_bs.png"
	
				markerContent.appendChild(markerImg);
	
	
				var markerNum = document.createElement("span");
				markerNum.className = 'marker-number';
				markerNum.innerHTML = i+1;
				markerContent.appendChild(markerNum);
	
				markers.setContent(markerContent); //更新点标记内容
		}
	
	
	
		maps.setZoom(10, 8)
		maps.add(markers); //添加到地图
	
	}



});

/**
 * 指定类型的变化驱动不同的界面显示
 * @param isSpecify
 * @param businessId
 */
function changeIsSpecify(isSpecify, businessId) {
	var hint = null;
	if (isSpecify == '1') {
		//指定人员
		$(".changeWork").hide();
		$(".changeTeam").hide();
		$(".changeUserId").show();

		if(id==null){
			selectUsersList(businessId);
		}else{
			getIfThereIsAViewByIsSpecifyAndBusinessId(isSpecify,businessId);
		}

	} else if (isSpecify == '2') {
		//指定部门
		$(".changeWork").hide();
		$(".changeUserId").hide();
		$(".changeTeam").show();
		console.log("id="+id);
		if(id==null){
			selectTeamList(businessId);
		}else{
			getIfThereIsAViewByIsSpecifyAndBusinessId(isSpecify,businessId);
		}

	} else {
		//指定工种
		console.log("id="+id);
		$(".changeTeam").hide();
		$(".changeUserId").hide();
		$(".changeWork").show();

		if(id==null){
			selectWorkerList(businessId);
		}else{
			getIfThereIsAViewByIsSpecifyAndBusinessId(isSpecify,businessId);
		}

	}
}

function mapsShow(){
	
}
/*
 * 提交表单
 */
function submitFom() {


	var taskName = $("#taskName").val();
	var taskStatement = $("#taskStatement").val();
	var taskType = $("#taskType input:checked").val();
	var taskLevel = $("#taskLevel input:checked").val();
	var taskCategories = $("#taskCategories input:checked").val();
	var isSpecify = $("#isSpecify input:checked").val();
	var lat = $("#lat").val();
	var log = $("#log").val();
	var lineId = $("#lineId").val();
	var businessId = "";
	var taskEndTime = "";
	if(taskCategories==1 && taskType == 3){
		taskEndTime = $("#taskEndTime").val();
	}
	
	if (isSpecify == "1") {
		//指定人
		$("input[name=userId]:checked").each(function () {
			if ($(this).val() != null) {
				businessId += $(this).val() + ",";
			}
		});
	} else if (isSpecify == "2") {
		//指定部门
		$("input[name=teamId]:checked").each(function () {
			if ($(this).val() != null) {
				businessId += $(this).val() + ",";
			}
		});
	} else {
		//指定工种
		$("input[name=workerId]:checked").each(function () {
			if ($(this).val() != null) {
				businessId += $(this).val() + ",";
			}
		});
	}
	if (businessId == null || businessId == '') {
		ly.toast("任务指定为空");
		return false;
	}
	if(taskType == 2){
		if (log == null || lat == '') {
			ly.toast("请选择地址");
			return false;
		}
	}
	
	/*var isUsing = $("#isUsing input:checked").val();*/
	var task = {
		'taskName': taskName,
		'taskStatement': taskStatement,
		'taskType': taskType,
		'taskLevel': taskLevel,
		'taskCategories': taskCategories,
		'isSpecify': isSpecify,
		'taskLat': lat,
		'taskLog': log,
		'taskEndTime':taskEndTime
	};
	var task2 = {
		'taskName': taskName,
		'taskStatement': taskStatement,
		'taskType': taskType,
		'taskLevel': taskLevel,
		'taskCategories': taskCategories,
		'isSpecify': isSpecify,
		'taskEndTime':taskEndTime
	};
	var obj = {};
	var url = site.apiUrl + "/moble/task/insertTask"; //apiUrl
	if (attendanceType == 1) {
		//新增
		obj = {
			'task': task,
			'businessId': businessId,
			'taskDetailsList': taskDetailsListTijaio,
		};
	} else {
		//修改
		var thisId = $("#id").val();
		obj = {
			'task': task2,
			'businessId': businessId,
			'taskDetailsList': taskDetailsListTijaio,
			'id': thisId
		};
	}
	if (taskType == "3") {
		if ($.trim(lineId) == "") {
			ly.toast("请选择任务路线");
			return false;
		} else {
			obj.task.lineId = lineId;
		}
	}

	console.log(obj);
	request({
		url: url,
		data: obj,
		type: "post",
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				if (attendanceType == 1) {
					ly.alert('保存成功', function () {
						ly.goto("task-list.html");
					});
				} else {
					ly.alert('修改成功', function () {
						ly.goto("task-list.html");
					});
				}
			} else {
				ly.toast(f.desc);
			}
		}
	});

}

//打开弹窗
function creatDetailsList(taskDetailsList) {
	$("#equipmentType").getSelect({
		type: "select",
		asName: "equipmentType",
		code: "equipmentType",
		default: ''
	});
	selectEquipmentListBack('', '', taskDetailsList);
	index = layer.open({
		title: false,
		type: 1,
		area: ['65%', '600px'], //设置宽度,高度自适应
		closeBtn: 0,
		content: $(".create_merchant"),
		success: function (layero, index) {
			$("#layui-layer" + index).find(".goback,.icon-close").on("click", function () {
				document.getElementById("formMerchant").reset();
				$("#layui-layer" + index).find(".valid").remove();
				$("#layui-layer" + index).find("div").removeClass('error success');
				layer.close(index);
			});
		}
	});
}

/**
 * 判断
 * @param isSpecify
 * @param businessId
 */
function getIfThereIsAViewByIsSpecifyAndBusinessId(isSpecify,businessId){
	console.log("businessId="+businessId);
	request({
		url: site.gateUrl + "/usersManagement/getIfThereIsAViewByIsSpecifyAndBusinessId",
		data: {
			'isSpecify': isSpecify,
			'businessId': businessId
		},
		type: "get",
		ajaxform: true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				var result = f.result;
				if(!result.exist){
					var notExistCause = result.notExistCause;
					console.log(notExistCause);
					if(isSpecify==1){
						if(notExistCause=="1"){
							$('#userId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的人员已经被删除</div>');
						}else if(notExistCause=="2"){
							$('#userId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的人员已经被禁用</div>');
						}
					}

					console.log(isSpecify)
					if(isSpecify==2){
						if(notExistCause=="1"){
							$('#teamId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的部门已经被删除</div>');

						}else if(notExistCause=="2"){
							$('#teamId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的部门已经被禁用</div>');
						}
					}

					if(isSpecify==3){
						if(notExistCause=="1"){
							$('#workerId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的工种已经被删除</div>');
						}else if(notExistCause=="2"){
							$('#workerId').append('<div class="col-8 text" ly-type="text" style="color:#F00">选择的工种已经被禁用</div>');
						}
					}

				}else{
					if(isSpecify==1){
						selectUsersList(businessId);
					}else if(isSpecify==2){
						selectTeamList(businessId);
					}else if(isSpecify==3){
						selectWorkerList(businessId);
					}
				}
				console.log(result.exist);
				console.log(result.notExistCause);
			}
		}
	});

}

//选择上级部门
function selectTeamList(businessId) {
	var list = new Array();
	request({
		url: site.gateUrl + "/back/team/selectTeamList",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1
		},
		type: "get",
		ajaxform: true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				/*var obj = {value:' ',display:'请选择'};
				list.push(obj);*/
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.teamName
						};
						list.push(obj);
					});
				}
				$("#teamId").getSelect({
					type: "checkbox",
					asName: "teamId",
					list: list,
					default: businessId
				});
			}
		}
	});
}

//选择设备
function selectEquipmentListBack(equipmentType, equipmentName, taskDetailsList) {

	var changeThisList = "";
	var listEquipmentId = "";
	$("#changeThisList").empty();
	if (taskDetailsList != null && taskDetailsList != '') {
		$.each(taskDetailsList, function (i, o) {
			changeThisList = "<tr class='deleteThisEquipment" + o.id + "'><input class='id' type='hidden' value='" + o.id + "'><td>" + (i + 1) + "</td><td>" + o.equipmentName + "</td><td onclick=\"deleteThisEquipment('" + o.id + "')\">删除</td></tr>";
			listEquipmentId += o.id + ",";
		});
		$("#changeThisList").append(changeThisList);
	}
	request({
		url: site.gateUrl + "/back/attendanceBack/selectEquipmentListBack",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1,
			'equipmentType': equipmentType,
			'equipmentName': equipmentName
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				var equipmentList = null;
				if (f.result.list != null && f.result.list != '') {
					$("#equipmentList").empty();
					obj = {};
					$.each(f.result.list, function (i, o) {
						var c = "";
						if (listEquipmentId != null && listEquipmentId != '') {
							if (o.id.indexOf(listEquipmentId) == -1) {
								c = "已选择";
							} else {
								c = "选择";
							}
						} else {
							c = "选择";
						}
						equipmentList += "<tr><td>" + o.equipmentName + "</td>" +
							"<td>" + o.equipmentTypeDisplay + "</td>" +
							"<td>" + o.lat + "</td><td>" + o.log + "</td><td>" + o.equipmentAddress + "</td>" +
							"<td class='equipment" + o.id + "' onclick=\"changeThisEquipment('" + o.id + "','" + o.equipmentName + "')\">" + c + "</td>";
					});
				}
				$("#equipmentList").append(equipmentList);
			}
		}
	});
}

/****
 * 
 * @param {Object} id
 * @param {Object} equipmentName
 */
function changeThisEquipment(id, equipmentName) {

	if ($(".equipment" + id).html() == '已选择') {
		ly.toast("已选择，不可重复选择");
		return false;
	}
	var length = parseFloat($("#changeThisList tr").length) + 1;
	var changeThisList = "<tr class='deleteThisEquipment" + id + "'><input class='id' type='hidden' value='" + id + "'><td class='taskFlow" + id + " paixu'>" + length + "</td><td>" + equipmentName + "</td>" +
		"<td><select id='taskOperation" + id + "' class=''></select></div></td><td><input type='text' class='ipt' id='detailsExplain" + id + "'></td><td onclick=\"deleteThisEquipment('" + id + "')\">删除</td></tr>";
	$("#changeThisList").append(changeThisList);
	$(".equipment" + id).html("已选择");
	selectDictBasicsWithGroup(id);

}

function deleteThisEquipment(id) {
	$(".deleteThisEquipment" + id).remove();
	$(".equipment" + id).html("选择");
	$(".paixu").each(function (i, o) {
		$(o).html(i + 1);
	});
}
//选择工种
function selectWorkerList(businessId) {
	var list = new Array();
	request({
		url: site.gateUrl + "/back/worker/selectWorkerList",
		data: {
			'num': 1,
			'size': 100,
			'isUsing': 1
		},
		type: "get",
		ajaxform: true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.workerName
						};
						list.push(obj);
					});
				}
				$("#workerId").getSelect({
					type: "checkbox",
					asName: "workerId",
					list: list,
					default: businessId
				});
			}
		}
	});
}

//选择用户
function selectUsersList(businessId) {
	var list = new Array();

	var teamId = "";
	var userType = "";
	var assumeOffice = "";
	var backstage_access_personnelstyle = window.localStorage.getItem("backstage-access-personnelstyle");
	if (backstage_access_personnelstyle == 1) {
		assumeOffice = "";
	} else {
		assumeOffice = "2";
		if(window.localStorage.getItem("backstage-access-teamId") == 'undefined'){
			teamId = '';
		}else{
			teamId = window.localStorage.getItem("backstage-access-teamId");
		}
		userType = window.localStorage.getItem("backstage_access_personnelstyle");
	}
	request({
		url: site.gateUrl + "/sUsers/selectUsersList",
		data: {
			'num': 1,
			'size': 1000,
			'isUsing': 1,
			'userType': userType,
			'teamId': teamId
			// 'assumeOffice': assumeOffice
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				var obj = {};
				if (f.result.list != null && f.result.list != '') {
					obj = {};
					$.each(f.result.list, function (i, o) {
						obj = {
							value: o.id,
							display: o.nickName
						};
						list.push(obj);
					});
				}
				$("#userId").getSelect({
					type: "checkbox",
					asName: "userId",
					list: list,
					default: businessId
				});
			}
		}
	});

}

//选择字典
function selectDictBasicsWithGroup(id) {
	var list = new Array();
	request({
		url: site.gateUrl + "/dictBasic/selectDictBasicsWithGroup",
		data: {
			'code': 'taskOperation'
		},
		type: "get",
		"ajaxform": true,
		callback: function (f) {
			console.log(f);
			if (f.code == "rest.success") {
				var options = '';
				if (f.result != null && f.result != '') {
					$.each(f.result, function (i, o) {
						options += "<option value='" + o.value + "'>" + o.display + "</option>"
					});
					$("#taskOperation" + id).append(options);
				}
			}
		}
	});
}

/***
 * 选择搜索
 */
function changeSelectTeamList() {

	var equipmentType = $('select[name=equipmentType] option:checked').val();
	var equipmentName = $("#equipmentName").val();
	selectEquipmentListBack(equipmentType, equipmentName, taskDetailsList);
}

